<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Amber - Pet Care Bootstrap 5 Template</title>

    <!-- Favicons -->
    <link rel="shortcut icon" href="assets/images/favicon.ico">

    <link rel="stylesheet" href="assets/css/vendor/vendor.min.css">
    <link rel="stylesheet" href="assets/css/plugins/plugins.min.css">
    <link rel="stylesheet" href="assets/css/style.min.css">
	<!-- jquery -->
	<script src="assets/jquery-3.6.0.min.js"></script>
	<script type="text/javascript">
		<!-- 导航栏的JS-开始 -->
		var itemHost = "http://localhost:3001/itemservice"
		//获取二级分类菜单，循环遍历添加菜单
		function getItemCat(){
			$.ajax({
				type:"get",
				url: itemHost + "/itemCat/getAll",
				success: function(result){
					if(result.status == 200){
						//console.log(result.data)
						var itemCatList = result.data
						//遍历一级分类菜单
						for(var i in itemCatList){
							var itemCatOne = itemCatList[i]
							var itemCatOneChildren = itemCatOne.children
							//遍历二级分类菜单
							if(i==0){
								for(var j in itemCatOneChildren){
									var itemCatTwo = itemCatOneChildren[j]
									$("#dog").append(
										`
											<li><a class="a" onclick="dogItem(${itemCatTwo.id})">${itemCatTwo.name}</a></li>
										`
									)
								}
							}
							if(i==1){
								for(var j in itemCatOneChildren){
									var itemCatTwo = itemCatOneChildren[j]
									$("#cat").append(
										`
											<li><a class="a" onclick="catItem(${itemCatTwo.id})">${itemCatTwo.name}</a></li>
										`
									)
								}
							}
							if(i==2){
								for(var j in itemCatOneChildren){
									var itemCatTwo = itemCatOneChildren[j]
									$("#other").append(
										`
											<li><a class="a" onclick="otherItem(${itemCatTwo.id})">${itemCatTwo.name}</a></li>
										`
									)
								}
							}
						}
					}					
				}
			})
		}
		//点击狗狗分类的某一个二级菜单，会获取item表中item_cat_id为此id的商品，并显示在shop.html页面
		function dogItem(id){
			$.ajax(itemHost+`/item/getData/${id}`)
			window.location.href="shop.html"
		}
		//点击猫咪分类的某一个二级菜单，会获取item表中item_cat_id为此id的商品，并显示在shop.html页面
		function catItem(id){
			$.ajax(itemHost+`/item/getData/${id}`)
			window.location.href="shop.html"
		}
		//点击其他分类的某一个二级菜单，会获取item表中item_cat_id为此id的商品，并显示在shop.html页面
		function otherItem(id){
			$.ajax(itemHost+`/item/getData/${id}`)
			window.location.href="shop.html"
		}
		//点击搜索框触发
		function searchItem(){
			let keyword = $("#search").val()
			$.ajax({
				type: "get",
				url: itemHost+"/item/search",
				data: {
					keyword:keyword
				},
				success: function(result){
					if(result.status==200){
						window.location.href = "shop.html"
					}
				}
			})
		}
		//退出登录
		function logout(){
			if(localStorage.getItem("accessToken") == null){
				alert("您还没有登录")
			}else{
				localStorage.removeItem("accessToken")
				localStorage.removeItem("refreshToken")
				sessionStorage.removeItem("userName")
				window.location.href = "index.html"
			}
		}
		/* 登录认证，如果没有登录，就不会跳转到account.html页面 */
		function accountAuth(){
			if(localStorage.getItem("accessToken")==null){
				alert("您还没有登录")
			}else{
				window.location.href = "account.html"
			}
		}
		/* 登录认证，如果没有登录，就不会跳转到cart.html页面 */
		function cartAuth(){
			if(localStorage.getItem("accessToken")==null){
				alert("您还没有登录")
			}else{
				window.location.href = "cart.html"
			}
		}
		<!-- 导航栏的JS-结束 -->
		var total_num = 0 //总件数
		var total_price = 0 //总价格
		var itemList = [] //付款的商品列表
		var userName = null
		var cartHost = "http://localhost:3001/cartservice"
		var orderHost = "http://localhost:3001/orderservice"
		//文档就绪
		$(function(){
			//获取萌宠商城导航栏信息
			getItemCat()
			//认证是否登录，如果已登录获取登录的用户名信息
			if(localStorage.getItem("accessToken")==null){
				alert("您还没登录")
				window.location.href="login.html"
			}else{
				userName = sessionStorage.getItem("userName")
				getCartAll(userName)
				console.log(userName)
			}
		})
		function getCartAll(userName){
			$.ajax({
				type: "get",
				url: cartHost + "/cart/getAll/"+userName,
				headers: {
					"Authorization": "Bearer "+localStorage.getItem("accessToken")
				},
				success: function(result){
					if(result.status == 201) console.log("购物车为空");
					else if(result.status == 200){
						console.log(result.data);
						let cartList = result.data;
						for(var i in cartList){
							let cartOne = cartList[i];
							$("#cart").append(
								`<tr id="cart-id-${cartOne.id}">
                                    <td class="pro-thumbnail"><a href="#"><img class="fit-image" src="${cartOne.images}" alt="Product" /></a></td>
                                    <td class="pro-title">${cartOne.title}</td>
                                    <td class="pro-price" id="cart-price-${cartOne.id}">${cartOne.price}</td>
                                    <td class="pro-quantity">
                                        <div class="quantity">
                                            <div class="cart-plus-minus">
                                                <input class="cart-plus-minus-box" id="cart-count-${cartOne.id}" value="0" type="text">
                                                <div class="dec qtybutton" onclick="decr(${cartOne.id},${cartOne.itemId})">-</div>
                                                <div class="inc qtybutton" onclick="incr(${cartOne.id},${cartOne.itemId})">+</div>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="pro-subtotal" id="cart-price-all-${cartOne.id}" >0</td>
                                    <td class="pro-remove" onclick="cartDeleteOne(${cartOne.id})"><i class="ti-trash"></i></td>
                                </tr>`
							)
						}
					}
				}
			})
		};
		//点击减号
		function decr(id,itemId){
			let a = $(`#cart-count-${id}`).attr("value");
			if(a>0) {
				//1.数量减少1
				a=a-1;
				$(`#cart-count-${id}`).attr("value",a);
				//2.同商品总价随数量减少
				if(a == 0){
					$(`#cart-price-all-${id}`).text(0);
				}
				b =  a * $(`#cart-price-${id}`).text();
				$(`#cart-price-all-${id}`).text(b);
				//3.总件数减一
				total_num--
				//4.总价格更新
				total_price = total_price - $(`#cart-price-${id}`).text()
				//5.更新购物车总数
				updateTotal(total_num,total_price)
				//6.更新商品列表集合（减）
				updateItemList_desc(itemId)
			}
		}
		//点击加号
		function incr(id,itemId){
			//1.数量增加1
			let a = $(`#cart-count-${id}`).attr("value");
			a++;
			$(`#cart-count-${id}`).attr("value",a);
			//2.同商品总价随数量增加
			b = a * $(`#cart-price-${id}`).text();
			$(`#cart-price-all-${id}`).text(b);
			//3.总件数加一
			total_num++
			//4.总价格更新
			total_price = parseInt(total_price) + parseInt($(`#cart-price-${id}`).text())
			//5.更新购物车总数
			updateTotal(total_num,total_price)
			//6.更新商品列表集合
			updateItemList_incr(itemId)
		}
		//从购物车里删除单个商品
		function cartDeleteOne(id){
			let flag = confirm("是否确认将此商品从购物车中移除")
			if(flag){
				$(`#cart-id-${id}`).remove();
				console.log(id);
				$.ajax({
					type: "delete",
					url: cartHost + "/cart/deleteOne",
					data: {
						id: id
					},
					headers: {
						"Authorization": "Bearer "+localStorage.getItem("accessToken")
					},
					success: function(result){
						if(result.status==200){
							console.log("删除成功")
						}
					}
				})
			}
		}
		function goShop(){
			window.location.href="shop.html";
		}
		function cartDeleteAll(){
			if(confirm("是否确定删除购物车内所有商品？")){
				$.ajax({
					type: "delete",
					url: cartHost + "/cart/deleteAll",
					data: {
						userName: userName
					},
					headers: {
						"Authorization": "Bearer "+localStorage.getItem("accessToken")
					},
					success:function(result){
						if(result.status == 200){
							window.location.reload();
							console.log("删除所有成功")
						}
					}
				})
			}
		}
		//更新购物车总数
		function updateTotal(total_num,total_price){
			$("#total-price").text("￥"+total_price)
			$("#total-num").text("￥10 x "+total_num)
			let total_amount = total_price + total_num * 10
			$("#total-amount").text("￥" + total_amount)
		}
		//点击支付触发此方法
		function pay(){
			//支付
			alert("您已支付成功")
			//生成订单
			addOrders()
			window.location.href = "cart.html"
		}
		//更新商品集合（减）
		function updateItemList_desc(itemId){
			//遍历商品集合，找到此id的对象，num--
			for(var i in itemList){
				if(itemList[i].id == itemId){
					itemList[i].num--
					console.log(itemList)
					if(itemList[i].num == 0){
						itemList.pop(itemList[i])
					}
				}
			}
		}
		//更新商品集合（加）
		function updateItemList_incr(itemId){
			//遍历商品集合，如果存在此id的对象，则num++,结束方法
			for(var i in itemList){
				if(itemList[i].id == itemId){
					itemList[i].num++
					console.log(itemList)
					return
				}
			}
			//如果不存在此id，则创建对象，添加对象
			var item = {}
			item.id = itemId
			item.num = 1
			itemList.push(item)
			console.log(itemList)
		}
		//生成订单
		function addOrders(){
			for(var i in itemList){
				$.ajax({
					type: "post",
					url: orderHost + "/order/addOrder",
					async: false,
					data: {
						userName: userName,
						itemId: itemList[i].id,
						num: itemList[i].num
					},
					headers: {
						"Authorization": "Bearer "+localStorage.getItem("accessToken")
					},
					success:function(result){
						if(result.status == 201){
							alert("订单生成出现错误")
						}
					}
				})
			}
			alert("订单生成成功")
		}
	</script>
</head>

<body>
    <!-- Header Section Start -->
    <div class="header section">

        <!-- Header Top Start -->
        <div class="header-top bg-name-primary">
            <div class="container">
                <div class="row align-items-center">

					<!-- Header Top Message Start -->
					<div class="col-12 col-lg-6">
					    <div class="header-top-msg-wrapper">
					        <a href="index.html" class="header-top-message">欢迎来到萌宠奇遇!</a>
					    </div>
					</div>
					<div class="col-12 col-lg-6">
					    <div class="header-top-settings">
							<a onclick="logout()" style="font-size: small; float: right; color: white;"> 退出登录 </a>
					        <a href="register.html" style="font-size: small; float: right; color: white;"> 注册&nbsp;&nbsp;|&nbsp;&nbsp; </a>
					        <a href="login.html" style="font-size: small; float: right; color: white;"> 登录&nbsp;&nbsp;|&nbsp;&nbsp;</a>
					    </div>
					</div>
					<!-- Header Top Message End -->

                </div>
            </div>
        </div>
        <!-- Header Top End -->

        <!-- Header Bottom Start -->
        <div class="header-bottom">
            <div class="header-sticky">
                <div class="container">
                    <div class="row align-items-center position-relative">

                        <!-- Header Logo Start -->
                        <div class="col-lg-3 col-md-4 col-6">
                            <div class="header-logo">
                                <a href="index.html"><img src="assets/images/logo/logo.png" alt="Site Logo" /></a>
                            </div>
                        </div>
                        <!-- Header Logo End -->

                        <!-- Header Menu Start -->
                        <div class="col-lg-6 d-none d-lg-block">
                            <div class="main-menu">
                                <ul>
                                    <li class="has-children">
                                        <a href="index.html">首页</a>
                                    </li>
                                    <li class="has-children position-static">
                                         <a href="#">萌宠商城</a>
                                        <ul class="mega-menu" id="itemCat">
                                            <li class="mega-menu-col">
                                                <h4 class="mega-menu-title">狗狗</h4>
                                                <ul class="m-b-n10" id="dog">
                                                    
                                                </ul>
                                            </li>
                                            <li class="mega-menu-col">
                                                <h4 class="mega-menu-title">猫咪</h4>
                                                <ul class="m-b-n10" id="cat">
                                                   
                                                </ul>
                                            </li>
                                            <li class="mega-menu-col">
                                                <h4 class="mega-menu-title">其他</h4>
                                                <ul class="m-b-n10" id="other">
                                                   
                                                </ul>
                                            </li>
                                            <li class="mega-menu-col">
                                                <div class="megamenu-image">
                                                    <a href="shop.html">
                                                        <img class="fit-image" src="assets/images/header/mega-menu.png" alt="Megamenu Image">
                                                    </a>
                                                </div>
                                            </li>
                                        </ul>
                                    </li>
                                    <li class="has-children">
                                        <a href="forum.html">萌宠论坛</a>
                                    </li>
                                    <li class="has-children">
                                        <a href="diary.html">萌宠日记</a>
                                    </li>
                                    <li><a href="login.html">登录</a></li>
                                    <li><a href="register.html">注册</a></li>
                                </ul>
                            </div>
                        </div>
                        <!-- Header Menu End -->

                        <!-- Header Action Start -->
                        <div class="col-lg-3 col-md-8 col-6">
                            <div class="header-actions">

                                <!-- Header Action Search Button Start -->
                                <div class="header-action-btn header-action-btn-search d-none d-md-flex">
                                    <div class="action-execute">
                                        <a class="action-search-open" href="javascript:void(0)"><i class="icon-magnifier icons"></i></a>
                                        <a class="action-search-close" href="javascript:void(0)"><i class="ti-close"></i></a>
                                    </div>
                                    <!-- Search Form and Button Start -->
                                    <form class="header-search-form" >
                                        <input type="text" class="header-search-input" placeholder="搜索商品" value="" id="search">
                                        <button class="header-search-button" onclick="searchItem()"><i class="icon-magnifier icons"></i></button>
                                    </form>
                                    <!-- Search Form and Button End -->
                                </div>
                                <!-- Header Action Search Button End -->

                                <!-- Header My Account Button Start -->
                                <a onclick="accountAuth()" class="header-action-btn header-action-btn-wishlist"">
                                    <i class="icon-user icons"></i>
                                </a>
                                <!-- Header My Account Button End -->

                                <!-- Header Action Button Start -->
                                <div class="header-action-btn header-action-btn-cart d-none d-sm-flex">
                                    <a onclick="cartAuth()" class="cart-visible">
                                        <i class="icon-handbag icons"><span style="font-size: medium;">&nbsp;购物车</span></i>
                                    </a>
                                </div>
                                <!-- Header Action Button End -->
                            </div>
                        </div>
                        <!-- Header Action End -->

                    </div>
                </div>
            </div>
        </div>
        <!-- Header Bottom End -->

    </div>
    <!-- Header Section End -->

    <!-- Breadcrumb Area Start -->
    <div class="section breadcrumb-area bg-name-bright">
        <div class="container">
            <div class="row">
                <div class="col-12 text-center">
                    <div class="breadcrumb-wrapper">
                        <h2 class="breadcrumb-title">购物车</h2>
                        <ul>
                          <li><a href="index.html">主页&nbsp;</a></li>
                            <li>购物车&nbsp;</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- Breadcrumb Area End -->

    <!-- Shopping Cart Section Start -->
    <div class="section section-margin">
        <div class="container">

            <div class="row">
                <div class="col-12">

                    <!-- Cart Table Start -->
                    <div class="cart-table table-responsive">
                        <table class="table table-bordered">

                            <!-- Table Head Start -->
                            <thead>
                                <tr>
                                    <th class="pro-thumbnail">商品图片&nbsp;</th>
                                    <th class="pro-title">商品名称</th>
                                    <th class="pro-price">价格(￥)&nbsp;</th>
                                    <th class="pro-quantity">数量&nbsp;</th>
                                    <th class="pro-subtotal">总价(￥)&nbsp;</th>
                                    <th class="pro-remove">移除&nbsp;</th>
                                </tr>
                            </thead>
                            <!-- Table Head End -->

                            <!-- Table Body Start -->
                            <tbody id="cart">
                                
                            </tbody>
                            <!-- Table Body End -->

                        </table>
                    </div>
                    <!-- Cart Table End -->

                    <!-- Cart Button Start -->
                    <div class="cart-button-section m-b-n20">

                        <!-- Cart Button left Side Start -->
                        <div class="cart-btn-lef-side m-b-20">
                            <a href="#" class="btn btn btn-gray-deep btn-hover-primary" onclick="goShop()">继续购物&nbsp;</a>
                            <!-- <a href="#" class="btn btn btn-gray-deep btn-hover-primary" onclick="updateCart()">更新购物车&nbsp;</a> -->
                        </div>
                        <!-- Cart Button left Side End -->

                        <!-- Cart Button Right Side Start -->
                        <div class="cart-btn-right-right m-b-20">
                            <a href="#" class="btn btn btn-gray-deep btn-hover-primary" onclick="cartDeleteAll()">清空购物车&nbsp;</a>
                        </div>
                        <!-- Cart Button Right Side End -->

                    </div>
                    <!-- Cart Button End -->

                </div>
            </div>

            <div class="row m-t-50">
                <div class="col-lg-6 me-0 ms-auto">

                    <!-- Cart Calculation Area Start -->
                    <div class="cart-calculator-wrapper">

                        <!-- Cart Calculate Items Start -->
                        <div class="cart-calculate-items">

                            <!-- Cart Calculate Items Title Start -->
                            <h3 class="title">购物车总数&nbsp;</h3>
                            <!-- Cart Calculate Items Title End -->

                            <!-- Responsive Table Start -->
                            <div class="table-responsive">
                                <table class="table">
                                    <tr>
                                        <td>所选商品总值&nbsp;</td>
                                        <td id="total-price">￥0</td>
                                    </tr>
                                    <tr>
                                        <td>运费总额&nbsp;</td>
                                        <td id="total-num">￥10 x 0</td>
                                    </tr>
                                    <tr class="total">
                                        <td>合计&nbsp;</td>
                                        <td class="total-amount" id="total-amount">￥0</td>
                                    </tr>
                                </table>
                            </div>
                            <!-- Responsive Table End -->

                        </div>
                        <!-- Cart Calculate Items End -->

                        <!-- Cart Checktout Button Start -->
                        <a class="btn btn btn-gray-deep btn-hover-primary m-t-30" onclick="pay()">去支付!&nbsp;</a>
                        <!-- Cart Checktout Button End -->

                    </div>
                    <!-- Cart Calculation Area End -->

                </div>
            </div>

        </div>
    </div>
    <!-- Shopping Cart Section End -->

    <!-- Footer Section Start -->
    <footer class="section footer-section">
        <!-- Footer Top Start -->
        <div class="footer-top bg-name-bright section-padding">
            <div class="container">
                <div class="row m-b-n40">
                    <div class="col-12 col-sm-6 col-lg-3 m-b-40" data-aos="fade-up" data-aos-duration="1000">
                        <div class="single-footer-widget">
                            <h1 class="widget-title">关于我们</h1>
                            <p class="desc-content">然后疼痛就会停止，疼痛就会受到折磨。</p>
                            <!-- Soclial Link Start -->
                            <div class="widget-social justify-content-start m-b-n10">
                                <a title="Twitter" href="#/"><i class="icon-social-twitter"></i></a>
                                <a title="Instagram" href="#/"><i class="icon-social-instagram"></i></a>
                                <a title="Linkedin" href="#/"><i class="icon-social-linkedin"></i></a>
                                <a title="Skype" href="#/"><i class="icon-social-skype"></i></a>
                                <a title="Dribble" href="#/"><i class="icon-social-dribbble"></i></a>
                            </div>
                            <!-- Social Link End -->
                        </div>
                    </div>
                    <div class="col-12 col-sm-6 col-lg-3 m-b-40" data-aos="fade-up" data-aos-duration="1200">
                        <div class="single-footer-widget">
                            <h2 class="widget-title">有用的链接</h2>
                            <ul class="widget-list">
                              <li><a href="wishlist.html">帮助和联系我们</a></li>
                                <li><a href="contact.html">退货和退款</a></li>
                                <li><a href="contact.html">线上商店</a></li>
                                <li><a href="contact.html">条款与条件</a></li>
                            </ul>
                        </div>
                    </div>
                    <div class="col-12 col-sm-6 col-lg-3 m-b-40" data-aos="fade-up" data-aos-duration="1400">
                        <div class="single-footer-widget">
                            <h2 class="widget-title">帮助</h2>
                            <ul class="widget-list">
                              <li><a href="wishlist.html">愿望清单</a></li>
                                <li><a href="contact.html">定价计划</a></li>
                                <li><a href="contact.html">物流跟踪</a></li>
                                <li><a href="contact.html">退换商品</a></li>
                            </ul>
                        </div>
                    </div>
                    <div class="col-12 col-sm-6 col-lg-3 m-b-40" data-aos="fade-up" data-aos-duration="1600">
                        <div class="single-footer-widget">
                            <h2 class="widget-title">发送时事通讯</h2>
                            <div class="widget-body">
                              <p class="desc-content m-b-20">订阅我们的时事通讯，首次购买可享受10%的折扣。</p>
                                <!-- Newsletter Form Start -->
                                <div class="newsletter-form-wrap p-t-5">
                                    <form id="mc-form" class="mc-form">
                                        <input type="email" id="mc-email" class="form-control email-box" placeholder="demo@example.com" name="EMAIL">
                                        <button id="mc-submit" class="newsletter-btn" type="submit">发送</button>
                                    </form>
                                    <!-- mailchimp-alerts Start -->
                                    <div class="mailchimp-alerts text-centre">
                                        <div class="mailchimp-submitting"></div><!-- mailchimp-submitting end -->
                                        <div class="mailchimp-success text-success"></div><!-- mailchimp-success end -->
                                        <div class="mailchimp-error text-danger"></div><!-- mailchimp-error end -->
                                    </div>
                                    <!-- mailchimp-alerts end -->
                                </div>
                                <!-- Newsletter Form End -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- Footer Top End -->
    </footer>
    <!-- Footer Section End -->

    <script src="assets/js/vendor.min.js"></script>
    <script src="assets/js/plugins.min.js"></script>

    <!--Main JS-->
    <script src="assets/js/main.js"></script>
	
	<!-- vue.js -->
	<!-- <script src="static/vue.js"></script>
	<script src="static/axios.min.js"></script>
	<script type="text/javascript">
		axios.defaults.baseURL = "http://localhost:8083"
		const APP = new Vue({
			el:"#app",
			data: {
				cartList: [],
				cartOne: {
					id: "",
					userId: "",
					itemId: "",
					title: "",
					price: "",
					image: ""
				},
				count: "1"
			},
			methods: {
				async getCartAll(){
					console.log("查询开始")
					let{data: result} = await axios.get("/cart/getAll")
					this.cartList = result.data
					console.log(this.cartList)
					console.log("查询结束")
				}
			},
			mounted(){
				this.getCartAll()
			}
		})
	</script> -->
</body>

</html>